let unityInstance = null
const channel = new BroadcastChannel(sessionStorage.getItem("channelKey"))

function setSize() {
    const unity_canvas = document.getElementById('unity-canvas')
    if (!unity_canvas) return
    unity_canvas.style.width = window.innerWidth + 'px'
    unity_canvas.style.height = window.innerHeight + 'px'
    // console.log('canvas width:', window.innerWidth, 'height:', window.innerHeight)
}

setSize()

function queueMessage(instance) {
    unityInstance = instance
    onMessage()
    delaySend(instance, 'init', 'IKConfig', IKConfig())
    delaySend(instance, 'init', 'IKJson', IKJson())
    delaySend(instance, 'init', 'location', Locations())
    delaySend(instance, 'init', 'modelRelation', modelRelation())
    delaySend(instance, 'init', 'modelScale', modelScale())
    delaySend(instance, 'init', 'bones', transBones())
    // delaySend(instance, 'run', 'startPart', [])
}

function dealMessage(type, key, message) {
    let data = []

    // { type: type, index: 0, size: 1, data: {}
    let strMessage = JSON.stringify(message)
    // if (strMessage.length > 7500) {
    let datas = []
    let length7500 = strMessage.length / 7500
    let mLength = Math.floor(length7500) === length7500 ?
        length7500 - 1 : Math.floor(length7500)
    for (let i = 0; i <= mLength; i++) {
        // let string = `type:${type},index:${i},size:${mLength + 1},data:`
        // let obj = {}
        // obj[key] = i === mLength ?
        //     strMessage.slice(i * 7500, strMessage.length-1) : strMessage.slice(i * 7500, (i + 1) * 7500)
        // datas.push(string+JSON.stringify(obj))
        let obj = {}
        obj[key] = i === mLength ?
            strMessage.slice(i * 7500, strMessage.length) : strMessage.slice(i * 7500, (i + 1) * 7500)
        datas.push({type: type, index: i, size: mLength + 1, data: obj})

        // let sData = JSON.stringify(datas[datas.length - 1])
        /*        let typeSplit = sData.split(",index:");
                let iType = typeSplit[0]
                let indexSplit = typeSplit[1].split(',size:');
                debugger
                let iIndex = parseInt(indexSplit[0])
                let sizeSplit = indexSplit[1].split(",data:")
                let iSize = parseInt(sizeSplit[0])
                let partialData = sizeSplit[1].slice(0,sizeSplit[1].length-1);*/
        // let partialData = JSON.parse(sData)

        // console.log(partialData)
        // console.log("data:", JSON.parse(partialData).data, "\n\nkey", JSON.parse(partialData).data.key)
        // let p = JSON.parse(partialData.data.bones)
        // console.log("\n\npartialData:", partialData, " \n\np:", p)
        // console.log('send', index, size)
    }
    // console.log('message:', datas)
    data = datas
    // }
    return data
}
function onMessage() {
    channel.onmessage = function (event) {
        let data = event.data;
        send(unityInstance,data.type,'values',data.data);
        // unityInstance.SendMessage('ReceiveWeb', 'ReceiveMessageFromJs', JSON.stringify(data))
    }
}
function delaySend(instance, type, key, message) {

    setTimeout(() => {
        let datas = dealMessage(type, key, message)
        try {
            for (let data of datas) {
                instance.SendMessage('ReceiveWeb', 'ReceiveMessageFromJs', JSON.stringify(data).trim())
                // console.log('delaySend', JSON.stringify(data))
            }
        } catch (e) {
            debugger
        }
    }, 50)
}
function send(instance, type, key, message){
    let datas = dealMessage(type, key, message)
    for (let data of datas) {
        // console.log(JSON.stringify(data))
        instance.SendMessage('ReceiveWeb', 'ReceiveMessageFromJs', JSON.stringify(data).trim())
    }
}

function run(instance) {
    let data = {type: 'run', data: {startPart: []}}
    setTimeout(() => {
        instance.SendMessage('ReceiveWeb', 'ReceiveMessageFromJs',
            JSON.stringify(data.startPart))
    }, 100)
}
